#include "head.h"

int get_string(const char *file, char *buff, size_t size) {
    FILE *fp = NULL;
    if ((fp = fopen(file, "rb")) == NULL) {
        return -1;
    }
    fseek(fp, 0, SEEK_END);
    size_t len = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    if (len >= size) {
        fprintf(stderr, "Buff size is less than the len of file\n");
        return -1;
    }

    int rsize = fread(buff, 1, len, fp);
    if (rsize != len) {
        fprintf(stderr, "Error happens in reading\n");
        return -1;
    }
    fclose(fp);
    return rsize;
}

int parse_conf(char *string) {
    const cJSON *master = NULL;
    const cJSON *slave = NULL;
    cJSON *conf = NULL;
    int status = 0;
    if ((conf = cJSON_Parse(string)) == NULL) {
        const char *err_ptr = cJSON_GetErrorPtr();
        if (err_ptr != NULL) {
            fprintf(stderr, "Error Before : %s\n", err_ptr);
            status = -1;
            goto end;
        }
    }
    master = cJSON_GetObjectItemCaseSensitive(conf, "Master");
    slave = cJSON_GetObjectItemCaseSensitive(conf, "Slave");

    cJSON *master_port = cJSON_GetObjectItemCaseSensitive(master, "MasterPort");
    cJSON *slave_port = cJSON_GetObjectItemCaseSensitive(slave, "SlavePort");
    printf("MasterPort = %d, ", master_port->valueint);
    printf("SlavePort = %d\n",slave_port->valueint);

end:
    cJSON_Delete(conf);
    return status;
}